package app.caihan.wanandroid.ui.login

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import app.caihan.scframe.api.retrofit2.checkResult
import app.caihan.scframe.base.viewmodel.BaseViewModel
import app.caihan.scframe.constant.DEBUG_TAG
import app.caihan.scframe.livedata.IntLiveData
import app.caihan.scframe.livedata.StringLiveData
import app.caihan.wanandroid.model.ScWanAndroidFactory
import app.caihan.wanandroid.model.bean.User
import com.blankj.utilcode.util.LogUtils

/**
 *
 *
 * @author Seven-C
 * @date 2020/8/22
 */
class LoginUiModel : BaseViewModel() {

    private val repository by lazy { ScWanAndroidFactory.makeWanRepository() }

    //用户名
    var username = StringLiveData()

    var loginTitle = StringLiveData()

    var loginTitle2 = StringLiveData()

    var type = IntLiveData()

    //密码(登录注册界面)
    var password = StringLiveData()

    var password2 = StringLiveData()

    val _userInfo: MutableLiveData<User> by lazy { MutableLiveData<User>() }

    // 对外暴露不可变的 LiveData，只能查询
    val userInfo: LiveData<User> = _userInfo

    fun login() {
        launchUI {
            showLoadingView()
            repository.login(username.value, password.value)
                .checkResult(
                    onSuccess = {
                        _userInfo.value = it
                        launchUI { repository.setUserDb(it) }
                        LogUtils.dTag(DEBUG_TAG, "login onSuccess $it")
                    },
                    onError = {
                        LogUtils.dTag(DEBUG_TAG, "login onError $it")
                    }
                )
            showContentView()
        }
    }

    fun registerAndlogin() {
        launchUI {
            showLoadingView()
            showContentView()
        }
    }
}